<template>
  <div class="user-managee">
    <div class="query-from">
      <el-form
        :inline="true"
        class="demo-form-inline"
        ref="searchForm"
        :model="table"
      >
        <el-form-item label="角色名" label-width="100px" prop="roleName">
          <el-input
            v-model="table.roleName"
            autocomplete="false"
            @keyup.enter="getRoleData"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="getRoleData"  v-has="'role-query'">查询</el-button>
          <el-button @click="reset()">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="base-table">
      <div class="action">
        <el-button type="primary" @click="add" v-has="'role-create'">新增</el-button>
      </div>
      <el-table v-loading="loading" :data="roleList" style="width: 100%">
        <el-table-column
          v-for="item in columns"
          :key="item.prop"
          :prop="item.prop"
          :label="item.label"
          :formatter="item.formatter"
        >
        </el-table-column>
        <el-table-column label="操作" min-width="100">
          <template #default="scope">
            <el-button type="primary" @click="edit(scope.row)" v-has="'role-edit'">编辑</el-button>
            <el-button type="primary" @click="SetPermissions(scope.row)" v-has="'role-setting'"
              >设置权限</el-button
            >
            <el-button type="danger" @click="deleteItem(scope.row)" v-has="'role-delete'"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- <div class="example-pagination-block">
     
    <el-pagination background layout="prev, pager, next" :total="total" @current-change="getpages" :page-size="pager.pageSize"/>
  </div> -->
      <el-dialog v-model="dialogVisible" @close="handleCancel">
        <el-form :model="form" ref="dialogForm" :rules="rule">
          <el-form-item label="角色名称" label-width="100px" prop="roleName">
            <el-input v-model="form.roleName" autocomplete="false" />
          </el-form-item>
          <el-form-item label="备注" label-width="100px" prop="remark">
            <el-input v-model="form.remark" autocomplete="false" />
          </el-form-item>
        </el-form>
        <template #footer>
          <span>
            <el-button type="primary" @click="handleSubmit()"> 确定 </el-button>
            <el-button @click="dialogVisible = !dialogVisible">取消</el-button>
          </span>
        </template>
      </el-dialog>
      <el-dialog v-model="dialogPermission">
        <el-form >
        <el-form-item label="角色名称" label-width="100px" >
          {{chooseRaw.roleName}}
        </el-form-item>
        <el-form-item label="权限" label-width="100px">
          <el-tree
            ref="treeRef"
            :data="menuList"
            show-checkbox
            default-expand-all
            highlight-current
            :props="defaultProps"
            node-key="_id"
          />
        </el-form-item>
        </el-form>
        <template #footer>
          <span>
            <el-button type="primary" @click="handle"> 确定 </el-button>
            <el-button @click="Cancel">取消</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, nextTick, toRaw } from "vue";
import { ElMessage, ElSteps, formatter } from "element-plus";
import utils from "../utils/index.js";
import api from "../api/index.js";

//定义校验规则
const rule = reactive({
  roleName: {
    required: true,
    message: "请填写名字",
  },
});
const action = ref("");
const loading = ref(true);
const dialogForm = ref(null);
const searchForm = ref(null);

const dialogVisible = ref(false);
const dialogPermission = ref(false);
const roleList = ref([]);
const menuList = ref([]);

const total = ref(0);
//定义模板列表
const table = reactive({
  roleName: "",
});
//表单数据
const form = ref({});

//选中的节点
const chooseRaw = ref();
const treeRef = ref();
const defaultProps = {
  children: "children",
  label: "menuName",
};


//发送删除请求
const deleteData = async (data) => {
  let result;
  try {
    result = await api.delteSelect(data);
  } catch (error) {
    console.log(error.data);
    ElMessage.success("删除失败，请稍后再试");
  }

  if (result.data.code == 200) {
    getUserList();

    ElMessage.success("删除成功");
  }
};

//动态定义表达格式
const columns = reactive([
  {
    label: "角色名称",
    prop: "roleName",
  },
  {
    label: "备注",
    prop: "remark",
  },
  {
    label: "权限列表",
    prop: "permissionList",
    formatter: (row, column, value) => {
      let res = []; // 存放结果

      const dfs = (data, ele, parent) => {
        data.forEach((menuEle) => {
          if (menuEle._id == ele) {
            res.push(parent);
          } else {
            if (menuEle.children) {
              parent = menuEle.menuName;

              dfs(menuEle.children, ele, parent);
            }
          }
        });
      };
      value.checkedKeys.forEach((ele) => {
        let parent;
        dfs(menuList.value, ele, parent);
      });

      let newRes = [...new Set(res)].toString();
      return newRes;
      // let names=[]
   
      // let halfKeys=value.halfCheckKeys||[]
      //   halfKeys.map((key)=>{
      //       let name= actionMap[key]
         
      //       if(key&&name){
      //         names.push(name)
      //       }
      //   })
     
      //   return names.join(',')
    },
  },
  {
    label: "更新时间",
    prop: "updateTime",
    formatter: (row, column, value) => {
      return utils.formateDate(new Date(value));
    },
  },
  {
    label: "创建时间",
    prop: "createTime",
    formatter: (row, column, value) => {
      return utils.formateDate(new Date(value));
    },
  },
]);

//请求角色数据
const getRoleList = async () => {
  getRoleData();
};

//请求角色列表方法
const getRoleData = async () => {
  loading.value = true;
  let result;

  try {
    result = await api.getRoleList(table);
  } catch (error) {
    let message = "请求失败";

    if (error.data.code == 40001) {
      message = error.data.msg;
    }
    let timer = setTimeout(() => {
      loading.value = false;
      ElMessage.error(message);
    }, 3000);
  }

  if (result.data.code == 200) {
    loading.value = false;
    roleList.value = result.data.data.list;
    ElMessage.success("请求数据成功");
    console.log(result.data.data.list);
  }
};

//定义角色提交事件
const handleSubmit = (dialogForm) => {
  dialogForm.validate((valid) => {
    if (valid) {
      let data = toRaw(form.value);
      data.action = action.value;
      // data.updateTime=`ISODate(${new Date().toISOString()})`
      addRoleData(data);
    }
  });
};
//将修改的数据提交到后台
const addRoleData = async (data) => {
  let result;
  try {
    result = await api.roleOperate(data);
    form.value = {
      parentId: [null],
    };
  } catch (error) {
    console.log(error.data);
    let message = "修改失败";

    if (error.data.code == 40001) {
      message = error.data.msg;
    }
    let timer = setTimeout(() => {
      dialogVisible.value = false;
      ElMessage.error(message);
    }, 3000);
  }

  if (result.data.code == 200) {
    dialogVisible.value = false;
    ElMessage.success("修改成功");
    getRoleData();
  }
};
// 新建角色
const add = () => {
  action.value = "create";
  dialogVisible.value = !dialogVisible.value;
};
//删除角色
const deleteItem = (row) => {
  let data = {
    action: "delete",
    _id: row._id,
  };
  addRoleData(data);
};
//修改角色
const edit = (row) => {
  action.value = "edit";
  dialogVisible.value = !dialogVisible.value;
  Object.assign(form.value, row);
};
//重置表单
const handleCancel = () => {
  dialogForm.value.resetFields();
  table.deptName = "";

  getRoleData();
};
const reset = () => {
  table.deptName = "";
  searchForm.value.resetFields();
  getRoleData();
};
//设置权限
const SetPermissions = (data) => {
  dialogPermission.value = !dialogPermission.value;
  console.log(data);
  chooseRaw.value = data;
  let { checkedKeys } = data.permissionList;
  setTimeout(() => {
    treeRef.value.setCheckedKeys(checkedKeys);
  });
};
//获取菜单列表

// 定义一个菜单映射表
let actionMap=ref({})

//定义建立映射表的方法
const getActionMap=(list)=>{

    let map={}
   const deep=(arr)=>{
        while(arr.length){
            let item=arr.pop()
            // item 代表每个对象，一级菜单
            if(item.children && item.action){
                // 二级菜单
                map[item._id]=item.menuName
            }
            if(item.children&& !item.action){
                deep(item.children)
            }
        }
   }
   deep(JSON.parse(JSON.stringify(list)))
   
   actionMap=map
  

}
// 定义菜单映射表

// 映射表的方法
const getmap=(list)=>{
   let map={}
   const deep=(arr)=>{
        while(arr.length){
            let item=arr.pop()
            // item 代表每个对象，一级菜单
            if(item.children && item.action){
                // 二级菜单
                map[item._id]=item.menuName
            }
            if(item.children&& !item.action){
                deep(item.children)
            }
        }
   }
   deep(JSON.parse(JSON.stringify(list)))
   actionmap.value=map
   console.log(map);
}
const getMenuList = async () => {
  let result;
  let data = {
    menuType: 1,
    menuState: 1,
  };
  try {
    result = await api.getMenuList(data);
  } catch (error) {
    console.log(error.data);
  }
  menuList.value = result.data.data;
   getActionMap(result.data.data)
  console.log(result.data.data);
};
//获取选中
const Cancel = (row) => {
  dialogPermission.value = false;
};

getMenuList();
getRoleList();
//修改权限
const handle = () => {
  let nodes = treeRef.value.getCheckedNodes();
  let parentKeys = []; //选中的元素的节点id
  let checkedKeys = []; //选中的父节点id
  let halfCheck = treeRef.value.getHalfCheckedKeys();
  nodes.forEach((ele) => {
    if (!ele.children) {
      //说明是按钮
      checkedKeys.push(ele._id);
    } else {
      //说明是菜单
      parentKeys.push(ele._id);
    }
  });
  console.log(checkedKeys, parentKeys.concat(halfCheck));
  let halfCheckKeys = parentKeys.concat(halfCheck);
  let data = {
    _id: chooseRaw.value._id,
    permissionList: {
      checkedKeys,
      halfCheckKeys,
    },
  };
  console.log(data);
  updatePermission(data);
};
//提交修改数据到后台
const updatePermission = async (data) => {
  let result;
  try {
    result = await api.rolePermission(data);
    chooseRaw.value = "";
    dialogPermission.value = false;
  } catch (error) {
    console.log(error.data);
    let message = "修改失败";

    if (error.data.code == 40001) {
      message = error.data.msg;
    }
    let timer = setTimeout(() => {
      ElMessage.error(message);
    }, 3000);
  }

  if (result.data.code == 200) {
    ElMessage.success("修改成功");
    getRoleData();
  }
};
</script>

<style lang="scss" scoped>
.query-from {
  width: 100%;
  background-color: white;
  .demo-form-inline {
    display: flex;
    align-items: center;
    justify-content: space-around;
    height: 60px;
    .el-form-item {
      margin: 0;
    }
  }
}
.base-table {
  overflow: hidden;
  .action {
    margin: 20px 20px;
  }
}

.user-managee {
  overflow: hidden;
}
.example-pagination-block {
  display: flex;
  justify-content: center;
  margin-top: 25px;
}
</style>
